﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Diagnostics;
using System.Configuration;
using System.Collections.Specialized;

namespace BizTalkOneService

{
    public class FreeDiskSpace
    {
        EventLog appLog = new EventLog();
        private List<FilePath> PathList = new List<FilePath>();
        private List<Counter> CounterList = new List<Counter>();
        public FreeDiskSpace()
        {

            var filePaths = ConfigurationManager.GetSection("disks") as NameValueCollection;
            if (filePaths != null)
            {
                foreach (var nameKey in filePaths.AllKeys)
                {
                    PathList.Add(new FilePath { FilePathKey = nameKey.ToString(), FilePathValue = filePaths.GetValues(nameKey).FirstOrDefault() });
                }
            }

            foreach (var Path in PathList)
            {
                try
                {
                    System.DiskFreeSpaceEx diskFreeSpaceEx = System.DiskInfo.GetDiskFreeSpaceEx(Path.FilePathValue);
                    if (null != diskFreeSpaceEx)
                    {

                        double TotalNumberOfBytes = Convert.ToDouble(diskFreeSpaceEx.TotalNumberOfBytes);
                        double FreeBytesAvailable = Convert.ToDouble(diskFreeSpaceEx.FreeBytesAvailable);
                        string Percentage = String.Format("{0:0.00}GB ({1:0}%)", (FreeBytesAvailable / 1024 / 1024 / 1024), (100 / TotalNumberOfBytes) * FreeBytesAvailable);
                        string Label = String.Format("{0} ({1:0.00}GB) ", Path.FilePathKey, TotalNumberOfBytes / 1024 / 1024 / 1024);
                        string Result = String.Format("{0:0}", (100 / TotalNumberOfBytes) * FreeBytesAvailable);
                        CounterList.Add(new Counter { CounterCategory = "FreeDiskSpace", CounterName = Label, CounterValue = Convert.ToInt32(Result), CounterValueString = Percentage });

                    }
                }
                catch (Exception ex)
                {
                    appLog.Source = Settings.EventLogSource;
                    appLog.WriteEntry(ex.Message);
                    //this.CounterList.Clear();
                    CounterList.Add(new Counter() { CounterCategory = "Error", CounterName = "FreeDiskSpace", CounterValueString = String.Format("{0}: {1}", Path.FilePathValue, ex.Message.ToString()) });
                }
            }
        }

        public List<Counter> GetFreeDiskSpace() 
        {
            return CounterList;
        }
    }
}